package com.czy.daishusys.ui.login;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.czy.daishusys.R;
import com.czy.daishusys.db.UserHelper;
import com.czy.daishusys.ui.BaseActivity;
import com.czy.daishusys.ui.MainActivity;
import com.czy.daishusys.utils.GetDeviceId;
import com.czy.daishusys.utils.MyLog;
import com.czy.daishusys.utils.PhoneUtils;
import com.easemob.cases.MessageHelper;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.model.HttpParams;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

/**
 * @author: Raven
 * @date: 2017/11/23 10:26
 * @email: xiexiaomeng_001@163.com
 * @description: daishu system app start page
 */

public class SplashActivity extends BaseActivity {

    @BindView(R.id.iv_splash)
    ImageView ivSplash;
    @BindView(R.id.btn_enter)
    Button btnEnter;

    private Handler mHandler;
    private Runnable mRunnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        if(UserHelper.getInstance().getDevicePid().equals("")) {
            RxPermissions rxPermissions = new RxPermissions(this);
            rxPermissions.request(Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(@NonNull Boolean aBoolean) throws Exception {
                            if (aBoolean) {
                                HttpParams params = new HttpParams();
                                String pid = new GetDeviceId(SplashActivity.this).getCombinedId();
                                params.put("pid",pid);
                                EasyHttp.getInstance().addCommonParams(params);//设置全局公共参数
                                MyLog.d("RAVEN","SplashActivity : pid= " + pid);
                                UserHelper.getInstance().setDevicePid(pid);
                                mHandler = new Handler();
                                mRunnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        intoMainActivity();
                                    }
                                };
                                mHandler.postDelayed(mRunnable, 2000);

                            } else {
                                PhoneUtils.ShowToastMessage(SplashActivity.this, "权限拒绝");
                                SplashActivity.this.finish();
                            }
                        }
                    });
        }else{
            intoMainActivity();
        }

    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initInjector() {
        UserHelper.getInstance().setIsLogined(initLoginState());
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void updateViews() {

    }

    @OnClick(R.id.btn_enter)
    protected void OnClick(View v) {
        MyLog.d("RAVEN","call btn enter");
        if (mHandler != null) {
            if (mRunnable != null) {
                mHandler.removeCallbacks(mRunnable);
            }
            intoMainActivity();
        }
    }

    /**
     * 每次开始登陆环信服务器
     */
    private void intoMainActivity() {
        MyLog.d("RAVEN","======into MainActivity====");
        btnEnter.setClickable(false);
        if (UserHelper.getInstance().isLogined()) {
            MessageHelper.getInstance().reset();
            MyLog.e("hep", UserHelper.getInstance().getAdminInfoModel(this).getImKey() + "|" + UserHelper.getInstance().getAdminInfoModel(this).getImPasswd());
            EMClient.getInstance().login(UserHelper.getInstance().getAdminInfoModel(this).getImKey(), UserHelper.getInstance().getAdminInfoModel(this).getImPasswd(), new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    MessageHelper.getInstance().getUserProfileManager().setCurrentUser(UserHelper.getInstance().getUserInfoModel(getApplicationContext()).getNickName(),
                            UserHelper.getInstance().getUserInfoModel(getApplicationContext()).getUserLogo());

                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();

                    MyLog.e("hep", "登录聊天服务器成功！" + UserHelper.getInstance().getAdminInfoModel(SplashActivity.this).getImKey() + "|" + UserHelper.getInstance().getAdminInfoModel(SplashActivity.this).getImPasswd());
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                    finish();
                }

                @Override
                public void onProgress(int progress, String status) {
                    MyLog.d("RAVEN","onProgress: status = " + status);
                }

                @Override
                public void onError(int code, String message) {
                    MyLog.d("hep", "登录聊天服务器失败！" + code + "|" + message);
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                    finish();
                }
            });
        } else {
            LoginActivity.navToLogin(this);
            finish();
        }
    }

    /**
     * 开屏后检测登录状态并选择跳转的界面
     */
    private void navToMainActivity() {
        if (isLogin()) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        } else {

        }
        this.finish();
    }

    /**
     * 当前是否登录
     *
     * @return boolean  已登录 true , 未登录 false
     */

    private boolean isLogin() {
        return UserHelper.getInstance().isLogined();
    }

    //用户是否存在判断
    private boolean initLoginState() {
        if (UserHelper.getInstance().getSessionInfoModel(this) == null || UserHelper.getInstance().getUserInfoModel(this) == null || UserHelper.getInstance().getAdminInfoModel(this) == null) {
            return false;
        } else {
            if (UserHelper.getInstance().getAdminInfoModel(this).getImKey() == null || UserHelper.getInstance().getAdminInfoModel(this).getImPasswd() == null) {
                return false;
            }
            MyLog.i(TAG, UserHelper.getInstance().getSessionInfoModel(this).toString());
            MyLog.i(TAG, UserHelper.getInstance().getUserInfoModel(this).toString());
            MyLog.i(TAG, UserHelper.getInstance().getAdminInfoModel(this).toString());
            return true;
        }
    }
}
